package com.yangye.niodemo.rpc.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author yangye
 * @date 2020/12/29
 */
public class SerDerUtil {

	private static ByteArrayOutputStream out = new ByteArrayOutputStream();

	public synchronized static byte[] ser(Object msg) {
		out.reset();

		ObjectOutputStream oos = null;
		byte[] res = null;

		try {
			oos = new ObjectOutputStream(out);
			oos.writeObject(msg);
			res = out.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return res;
	}

	public static Object der(byte[] bytes) {
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		try {
			ObjectInputStream ois = new ObjectInputStream(in);
			return ois.readObject();
		} catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
}
